import { Model, DataTypes, Optional } from 'sequelize';
import { sequelize } from '../../config/database';
import User from './User';
import Room from './Room';

// 粉丝团接口
interface FanClubAttributes {
  userId: string;
  roomId: string;
  level: number;
  name?: string | null;
  createdAt?: Date;
}

// 创建时可选的属性
interface FanClubCreationAttributes extends Optional<FanClubAttributes, 'createdAt'> {}

// 粉丝团模型类
class FanClub extends Model<FanClubAttributes, FanClubCreationAttributes> implements FanClubAttributes {
  public userId!: string;
  public roomId!: string;
  public level!: number;
  public name!: string | null;
  
  // 时间戳
  public readonly createdAt!: Date;
}

// 初始化模型
FanClub.init(
  {
    userId: {
      type: DataTypes.STRING,
      primaryKey: true,
      allowNull: false
    },
    roomId: {
      type: DataTypes.STRING,
      primaryKey: true,
      allowNull: false
    },
    level: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0
    },
    name: {
      type: DataTypes.STRING,
      allowNull: true
    }
  },
  {
    sequelize,
    tableName: 'fan_clubs',
    modelName: 'FanClub',
    timestamps: true,
    updatedAt: false // 粉丝团关系不需要更新时间
  }
);

// 设置关联关系（禁用外键约束）
FanClub.belongsTo(User, { foreignKey: 'userId', as: 'user', constraints: false });
FanClub.belongsTo(Room, { foreignKey: 'roomId', as: 'room', constraints: false });

User.hasMany(FanClub, { foreignKey: 'userId', as: 'fanClubs', constraints: false });
Room.hasMany(FanClub, { foreignKey: 'roomId', as: 'fanClubs', constraints: false });

export default FanClub;